package concurrency.chapter7;

public class SynchronizedRunnable2 implements Runnable {
    //readonly shared data.
    private static final int MAX = 500;
    //static可以实现多个线程访问同一个数据，不会出现重复数据，但生命周期太长
    private static int index = 1;

    @Override
    public void run() {
        while (true) {
            if (ticket())
                break;
        }
    }

    //同步方法
    private synchronized boolean ticket() {
        //synchronized (this) {
        //1、getField
        if (index > MAX)
            return true;
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //index++  ==> index=index+1
        //1、get Field index
        //2、index+1
        //3、put Field index
        System.out.println(Thread.currentThread().getName() + "的号码是：" + index++);
        return false;
        //}
    }
}
